package com.base.library.base

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.util.SparseArray
import com.base.library.ext.getString
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import com.base.library.R
import com.base.library.ext.getString
import com.base.library.ext.send
import com.base.library.utils.LogUtils
import com.base.library.widget.MultipleStatusView
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import java.util.concurrent.atomic.AtomicInteger

abstract class BaseVM : ViewModel(), DefaultLifecycleObserver {
    protected open var TAG = this.javaClass.simpleName

    /**
     * 是否要关闭activity
     */
    val isClosedSelf: MutableSharedFlow<Boolean?> by lazy {
        MutableSharedFlow()
    }

    private val onActivityResults: SparseArray<ActivityCallback> = SparseArray()

    private val requestCode: AtomicInteger by lazy {
        AtomicInteger(0)
    }
    val mStartActivityFlow: MutableSharedFlow<ActivityStarterResult> = MutableSharedFlow()
    val mToastContentFlow: MutableSharedFlow<CharSequence?> = MutableSharedFlow()
    val mLoadingDialogFlow: MutableSharedFlow<CharSequence?> = MutableSharedFlow()
    val mHideKeyboard: MutableSharedFlow<Boolean?> = MutableSharedFlow()

    /**
     * 页面状态
     */
    val mPageStatus = MutableStateFlow(MultipleStatusView.State.STATUS_CONTENT)

    /**
     * 页面状态文本
     */
    val mPageStatusHintText = MutableStateFlow<String?>(null)

    /**
     * 页面状态按钮文本
     */
    val mPageStatusButtonText = MutableStateFlow<String?>(null)

    var intent: Intent? = null
        private set

    /**
     * fragment使用
     */
    var arguments: Bundle? = null

    /**
     * 初始化数据
     */
    abstract fun initData()

    open fun onNewIntent(intent: Intent?) {
        LogUtils.i(TAG, "onNewIntent $intent")
    }

    fun setIntent(intent: Intent?) {
        this.intent = intent
    }

    fun showLoadingDialog(text: String? = R.string.str_loading.getString()) {
        mLoadingDialogFlow.send(text)
    }

    fun dismissLoadingDialog() {
        mLoadingDialogFlow.send(null)
    }

    /**
     * 显示页面加载中
     */
    open fun showLoading() {
        changePageStatus(MultipleStatusView.State.STATUS_LOADING, null, null)
        refresh()
    }


    /**
     * 显示页面内筒
     */
    open fun showContent() {
        changePageStatus(MultipleStatusView.State.STATUS_CONTENT, null, null)
    }

    /**
     * 显示无网络
     */
    open fun showNoNetwork(
        text: String? = R.string.str_load_error.getString(),
        btnText: String? = R.string.str_retry.getString()
    ) {
        changePageStatus(MultipleStatusView.State.STATUS_NETWORK_ERROR, text, btnText)
    }

    /**
     * 显示错误布局
     */
    open fun showError(
        text: String? = R.string.str_load_error.getString(),
        btnText: String? = R.string.str_retry.getString()
    ) {
        changePageStatus(MultipleStatusView.State.STATUS_ERROR, text, btnText)
    }

    /**
     * 显示空布局
     */
    open fun showEmpty(text: String? = R.string.str_empty.getString()) {
        changePageStatus(MultipleStatusView.State.STATUS_EMPTY, text, null)
    }

    /**
     * 修改页面状态
     */
    private fun changePageStatus(status: Int, text: String? = null, btnText: String? = null) {
        mPageStatus.value = status
        mPageStatusHintText.value = text
        mPageStatusButtonText.value = btnText
    }

    fun hideKeyboard() {
        mHideKeyboard.send(true)
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
    }

    override fun onCleared() {
        super.onCleared()
    }

    /**
     * 关闭Activity
     */
    fun closeSelf() {
        isClosedSelf.send(true)
    }

    /**
     * 启动Activity
     */
    fun startActivity(
        activityClass: Class<out Activity>,
        flags: Int? = null,
        extras: Bundle? = null,
        callback: ActivityCallback? = null
    ) {
        startActivity("", activityClass.name, flags, extras, callback)
    }

    /**
     * 启动Activity
     */
    fun startActivity(
        pkgName: String,
        className: String,
        flags: Int? = null,
        extras: Bundle? = null,
        callback: ActivityCallback? = null
    ) {

        val intent = Intent().apply {
            component = ComponentName(pkgName, className)
            extras?.also {
                replaceExtras(it)
            }
            flags?.also {
                setFlags(it)
            }
        }

        startActivity(intent, callback)
    }

    /**
     * 启动Activity 仅用于构造Uri action这类的intent 主要不要让ViewModel持有Context 避免内存泄露
     */
    fun startActivity(
        intent: Intent, callback: ActivityCallback? = null
    ) {
        var nextInt = -1

        callback?.also {
            nextInt = requestCode.getAndAdd(1)
            onActivityResults.put(nextInt, callback)
        }
        mStartActivityFlow.send(ActivityStarterResult(intent, nextInt))
    }

    /**
     * 显示Toast
     */
    fun showToast(toastContent: CharSequence) {
        mToastContentFlow.send(toastContent)
    }

    fun onActivityResult(code: Int, result: Intent?, resultCode: Int) {
        onActivityResults.get(code)?.invoke(resultCode, result)
        onActivityResults.remove(code)
    }

    open fun refresh() {
    }

}
typealias ActivityCallback = (resultCode: Int, data: Intent?) -> Unit